package com.wcy.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wcy.annotation.aop.PreAuth;
import com.wcy.entity.UserRole;
import com.wcy.entity.queryVo.QueryConvertor;
import com.wcy.service.IUserRoleService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/userRole")
public class UserRoleController {

    @Autowired
    private IUserRoleService userRoleService;

    @PreAuth("USERROLE:QUERY")
    @GetMapping("/page")
    @SentinelResource(value = "#root.targetClass + '.' + #root.methodName")
    public ResponseEntity<Page<UserRole>> getPage(@RequestParam(defaultValue = "1") int pageNum,
                                                  @RequestParam(defaultValue = "10") int pageSize,
                                                  HttpServletRequest request) {
        String queryData = request.getHeader("X-Query-Data");
        QueryWrapper wrapper = new QueryConvertor(queryData).convert(true);
        Page<UserRole> page = userRoleService.page(new Page<>(pageNum, pageSize),wrapper);
        return ResponseEntity.ok(page);
    }

    @PreAuth("USERROLE:QUERY")
    @GetMapping("/list")
    @SentinelResource(value = "#root.targetClass + '.' + #root.methodName")
    public ResponseEntity<List<UserRole>> getList(HttpServletRequest request) {
        String queryData = request.getHeader("X-Query-Data");
        QueryWrapper wrapper = new QueryConvertor(queryData).convert(true);
        List<UserRole> list = userRoleService.list(wrapper);
        return ResponseEntity.ok(list);
    }

    @PreAuth("USERROLE:ADD")
    @PostMapping("/add")
    @SentinelResource(value = "#root.targetClass + '.' + #root.methodName")
    public ResponseEntity<Void> add(@RequestBody UserRole userRole) {
        userRoleService.save(userRole);
        return ResponseEntity.ok().build();
    }

    @PreAuth("USERROLE:ALTER")
    @PutMapping("/update")
    @SentinelResource(value = "#root.targetClass + '.' + #root.methodName")
    public ResponseEntity<Void> update(@RequestBody UserRole userRole) {
        userRoleService.updateById(userRole);
        return ResponseEntity.ok().build();
    }

    @PreAuth("USERROLE:DELETE")
    @DeleteMapping("/delete/{id}")
    @SentinelResource(value = "#root.targetClass + '.' + #root.methodName")
    public ResponseEntity<Void> delete(@PathVariable Integer id) {
        userRoleService.removeById(id);
        return ResponseEntity.ok().build();
    }
}